package com.fingard.dsp.bank.directbank.chinapay06;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;

import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

public class ChinaPay06Statement extends ChinaPay06Base implements IStatement {
	@Override
	public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
		RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();

        String[] tmpPosRecRespHeader = getPosRecStatement(p_reqQrySttm, retAts);
        String tmpPosRecTotalNum = retAts.totalNum;
        
        if (retAts.getWrittenRdCount() == 0) {
        	if ("-1".equals(tmpPosRecRespHeader[0])) {
	            retAts.writeRespCode("-1");
	            retAts.writeRespInfo(tmpPosRecRespHeader[1]);
	        } else {
	        	retAts.writeRespCode("0");
				retAts.writeRespInfo("交易为空");
	        }
		} else {
			retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(tmpPosRecTotalNum)));
		}

        retAts.writeEnd();
        return retAts;
	}

	private String[] getPosRecStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
		String[] respHeader = new String[]{"",""};
		
		String respCode = "";
		String respInfo = "";
		
		retAts.totalNum = "0";
		int totalNum = 0;
		
		try {
			FtpSet ftpSet = bankFront.getFtpSet("pos");

            ftpSet.downDir = StringHelper.trimEnd(ftpSet.getDownDir("pos"), "/") + "/" + p_reqQrySttm.busDate;
			WriteBankLogLn2("北京银联POS对账单FTP服务器地址:" + ftpSet.serverIP + ":" + ftpSet.port);
			
			StringBuilder sbFileContent = new StringBuilder();
			String downFileName = getBankConfig().getValueAsString("merchantId") + p_reqQrySttm.busDate + "001.txt";
			WriteBankLogLn2("北京银联POS对账单所在服务器路径:" + ftpSet.downDir + "/" + downFileName);
			
			String localFilePath = createTempFileDirectory() + File.separator + downFileName;
            WriteBankLogLn2("北京银联POS对账单保存本地路径:" + localFilePath);
            
            FtpReceiver ftpReceiver = null;
			String posRecRequestType = getBankConfig().getValueAsString("posRecRequestType");
			if ("ftp".equals(posRecRequestType.toLowerCase())) {
				FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
	            ftpReceiver = ftpPortClient.downloadFile(downFileName, localFilePath);
			} else if ("sftp".equals(posRecRequestType.toLowerCase())) {
				SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
				String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + downFileName;
				WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
				ftpReceiver = sftpPortClient.downloadFile("",sftpFilePath, localFilePath);
			}
            if (ftpReceiver.isCompleted) {
            	if (sbFileContent.length() > 0) {
            		sbFileContent.append("\n");
            	}
            	sbFileContent.append(FileHelper.readFileText(localFilePath, getCharset("UTF-8", "pos")));
            } else {
            	respCode = "-1";
    			respInfo = "北京银联POS对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
            }
			if (StringHelper.hasAnyChar(sbFileContent.toString())) {
				String tmpStrRet = sbFileContent.toString();
				WriteBankLogLn2("北京银联POS对账单响应数据:\r\n" + tmpStrRet);
				
				respCode = "0";
				
				StringReader strReader = new StringReader(tmpStrRet);
				BufferedReader tmpReader = new BufferedReader(strReader);
				
				boolean isContinue = false;
				while(true) {
					String eachline = tmpReader.readLine();
					if(eachline == null){
						break;
					}
                    if ("".equals(eachline)) {
                        continue;
                    }
					String[] detailNodes = eachline.split("`~");
					if (p_reqQrySttm.actNum.equals(detailNodes[1].trim())) {
						totalNum++;
						isContinue = true;
						RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
						
						if (StringHelper.hasAnyChar(detailNodes[4])) {
							tmpRetDetail.askNumber = detailNodes[4].trim();
						}
						
						tmpRetDetail.cdFlag = "22";
						
						if (StringHelper.hasAnyChar(detailNodes[11])) {
							tmpRetDetail.amount = StringHelper.amountDivide100(detailNodes[11].trim());
						}
						
						if (StringHelper.hasAnyChar(detailNodes[15])) {
							tmpRetDetail.fee = StringHelper.amountDivide100(detailNodes[15].trim());
						}
						
						tmpRetDetail.busTime = detailNodes[6];
						
						if (StringHelper.hasAnyChar(detailNodes[7])) {
							tmpRetDetail.oppAct = detailNodes[7].trim();
						}
						
						if (StringHelper.hasAnyChar(detailNodes[8])) {
							tmpRetDetail.oppActName = detailNodes[8].trim();
						}
						
						if ("2".equals(detailNodes[13].trim())) {
							tmpRetDetail.transState = TransState.Success;
						} else {
							tmpRetDetail.transState = TransState.Fail;
						}
	    				
		        		retAts.writeRetDetail(tmpRetDetail);
					}
				}
				
				if (!isContinue) {
					respCode = "0";
					respInfo = "没有符合条件的记录!";
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			respCode = "-1";
			respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.totalNum = String.valueOf(totalNum);
		
		respHeader[0] = respCode;
		respHeader[1] = respInfo;
		
		return respHeader;
	}
}
